<?php
namespace app\xdk\model;
use think\Model;
use \Firebase\JWT\JWT;
class Mogo extends Model
{
    // 继承后可以直接通过类变量得到用户id
    protected $USER_ID;
    /**
     * 通过token获取当前用户的token
     * @return object
     */
    protected function currentUser(){
        $jwt = request()->header('Authorization');
        $key = config('mogosdk_key')||'MogoSDK';
        if(!$jwt) $this->forceReturn("miss token");

        try{
            $user = JWT::decode($jwt, $key, array('HS256'));
            return $user;
        }catch (\Exception $exception){
            $this->forceReturn("token invalid");
        }
    }

    /**
     * 用户登录
     * @param $user array 需要保存的用户信息
     * @return string 返回token
     */
    protected function userLogin($user){
        $key = config('mogosdk_key')||'MogoSDK';
        $token = $user;
        return JWT::encode($token, $key);
    }

    /**
     * 检查token状态 如果没有则返回未登录 有则返回用户信息
     * @return object
     */
    protected function checkToken(){
        $user = $this->currentUser();
        if($user){
            $this->USER_ID = $user->id;
            return json($user);
        }else{
            $this->forceReturn();
        }
    }

    public function pay(){}

    /**
     * 强制返回错误json
     * @param string $error
     */
    public function forceReturn($error="未登录"){
        echo json_encode(['error'=>$error]);
        header("HTTP/1.1 404 Not Found");
        header("Status: 404 Not Found");
        header('Content-type: application/json; charset=utf-8');
        exit;
    }
    
}
